package com.musiklegal;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.musiklegal.MyD.MusicAdapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class Send extends Activity {
    /** Called when the activity is first created. */
	static String usernameto;
	EditText etxt_mess ;
	TextView etxt_name;
	Button attach,clear;
	View attachment;
	SongD selected;
	ImageView img,res;
	TextView title,artist;
	Handler h=new Handler();
	Dialog d;
	Bitmap bm;
	public void onResume()
	{
		super.onResume();
		
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send);
        attach = (Button) findViewById(R.id.attach);
        etxt_mess = (EditText) findViewById(R.id.Mess);
        etxt_name = (TextView) findViewById(R.id.reciever);
        attachment = findViewById(R.id.attachment);
        img = (ImageView) findViewById(R.id.pictal);
        title = (TextView) findViewById(R.id.judultext);
        artist = (TextView) findViewById(R.id.artisttext);
        attach = (Button) findViewById(R.id.attach);
        clear = (Button) findViewById(R.id.clearbut);
        res = (ImageView) findViewById(R.id.pictmessage);
        if(usernameto!=null)
        	{
        		etxt_name.setText(usernameto);
        		
        		new Thread(new Runnable(){

					public void run() {
						
						
						
						try {
							String pict = Inbox.getPictUrl(usernameto);
							URL url = new URL(pict);
							InputStream is = url.openConnection().getInputStream();
							bm = BitmapFactory.decodeStream(is);
							h.post(new Runnable(){

								public void run() {
									// TODO Auto-generated method stub
									//res.setImageBitmap(bm);
									if(bm!=null)
										res.setImageBitmap(bm);
									else
										res.setImageResource(R.drawable.oc2);
								}});
							
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						
						
					}}).start();
        		
        	}
        attach.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				showChoice();
				
			}});
        	
        Button send = (Button) this.findViewById(R.id.send);
        clear.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				clearAttach();
			}});
        
        send.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				if(MusikLegal.internet(getApplicationContext()))
				{
				trySend();
				}
			else
			{
				Toast.makeText(getApplicationContext(), "You are unable to connect", Toast.LENGTH_SHORT).show();
            	}	
			
			}
		});
    }
    void clearAttach()
    {
    	attachment.setVisibility(View.GONE);
    	clear.setVisibility(View.GONE);
    	selected = null;
    }
  
    void trySend()
    {
    	
    	
		
		
		
		String username = MusikLegal.mPreferences.getString("UserName", "No");
    	String mess = etxt_mess.getText().toString();
    	String name = etxt_name.getText().toString();
    	
    	
    	DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://secure.musiklegal.com/message/send");
        List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
        nvps.add(new BasicNameValuePair("SENDER", username));
        nvps.add(new BasicNameValuePair("MESSAGE", mess));
        nvps.add(new BasicNameValuePair("RECEIVER", name));
        if(selected!=null)
        {
        	String Attach =selected.idRing+"|"+selected.api;
        	nvps.add(new BasicNameValuePair("ATTACHMENT",Attach));
        	//Log.d("attach",selected.idRing);
        	//Log.d("attach",selected.api );
        	 
        }
        try {   
      	  	UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
            
            httppost.setEntity(p_entity);
            
            HttpResponse response = client.execute(httppost);
            HttpEntity responseEntity = response.getEntity();
            

            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            
            LoginHandler myLoginHandler = new LoginHandler();
            xr.setContentHandler(myLoginHandler);
            xr.parse(retrieveInputStream(responseEntity));
            ParsedLoginDataSet parsedLoginDataSet = myLoginHandler.getParsedLoginData();
            
            	
            
            if (parsedLoginDataSet.getExtractedString().equals("SUCCESS")) 
            {
            	
            	AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        		alertDialog.setTitle("Success");
        		alertDialog.setMessage("Pesan anda telah dikirim");
        		alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
        			public void onClick(DialogInterface dialog, int which) {
        				
                          finish();
        			}
        		});
        		alertDialog.setIcon(R.drawable.oc2);
        		alertDialog.show();
              
             
            }
            else
            	{
            	AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        		alertDialog.setTitle("Fail");
        		alertDialog.setMessage("Gagal mengirim pesan");
        		alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
        			public void onClick(DialogInterface dialog, int which) {
        			
                          finish();
        			}
        		});
        		alertDialog.setIcon(R.drawable.oc2);
        		alertDialog.show();
            	
            	
            	}
      } catch (Exception e)
      {
          
      }
    
    
    
    }
    private InputSource retrieveInputStream(HttpEntity httpEntity) {
        InputSource insrc = null;
        try {
              insrc = new InputSource(httpEntity.getContent());
        } catch (Exception e) {
        }
        return insrc;
  } 
    EditText searchtext;
    Button search;
    ListView lv;
    List<SongD> daftar;
    Dialog dialog;
    List<SongD> temp;
    MusicAdapter ma;
    void showChoice()
    {
    	daftar= MusikLegal.listDownload;
    	d = new Dialog(Send.this);
    	temp = new ArrayList<SongD>();
    	temp.addAll(daftar);
		
		LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflate.inflate(R.layout.choice, (ViewGroup) findViewById(R.id.theroot));
		d.setTitle("Attach Music");
		searchtext = (EditText) v.findViewById(R.id.searchtext);
		search= (Button) v.findViewById(R.id.srcdiag);
		lv = (ListView) v.findViewById(R.id.listlagu);
		ma = new MusicAdapter(Send.this,daftar);
		lv.setAdapter(ma);
		lv.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				selected = temp.get(arg2);
				showAttach();
				d.dismiss();
				temp.clear();
				temp.addAll(daftar);
				
					
			}});
		
		search.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				
				String sr = searchtext.getText().toString();
				temp.clear();
				if(!sr.equals(""))
				{
					for(SongD s:daftar)
					{
						if(s.title.toLowerCase().contains(sr)||s.artist.toLowerCase().contains(sr))
							temp.add(s);
					}
					ma.list=temp;
					lv.invalidateViews();
				}
				
				
			}});
		/*d.setPositiveButton("Close", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				
			}
		});*/
		
		/*d.setNegativeButton("Clear", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				selected=null;
				attachment.setVisibility(View.GONE);
				dialog.dismiss();
			}
		});*/
		
		//d.setIcon(R.drawable.oc2);
		d.setContentView(v);
		
		d.show();
		
    }

    void showAttach()
    {
    	attachment.setVisibility(View.VISIBLE);
    	String tes = MusikLegal.albumArtFolder+selected.albumid+".jpg";
    	clear.setVisibility(View.VISIBLE);
    	//Toast.makeText(getApplicationContext(), tes, Toast.LENGTH_SHORT).show();
    	
    	Bitmap bm = BitmapFactory.decodeFile(tes);
    	img.setImageBitmap(bm);
    	title.setText(selected.title);
    	artist.setText(selected.artist);
    }
    
    public void onDestroy()
    {
    	super.onDestroy();
    	usernameto=null;
    }
}